global class QuoteWebService {
    // 报价拷贝按钮
    WebService static String copyQuote(String qid) {
        String rtn = '';
        try {
            // 获取报价
            Schema.DescribeSobjectResult m = Quote.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', ';
                }
                fields += field;
            }
            sql += fields;
            sql += ' from Quote where Id = \'' + qid + '\'';
            Quote oldQuote = Database.query(sql);

            // 获取报价产品
            m = QuoteProduct__c.sObjectType.getDescribe();
            fieldMap = m.fields.getMap();

            sql = 'select ';
            fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', ';
                }
                fields += field;
            }
            sql += fields;
            sql += ' from QuoteProduct__c where Quote__c = \'' + qid + '\'';
            List<QuoteProduct__c> oldList = Database.query(sql);

            // 拷贝报价
            Quote newQuote = oldQuote.clone(false, true);
            newQuote.Status = '草案中';
            // newQuote.Contract__c = null;
            // newQuote.IsAdjustQuote__c = false;
            // newQuote.AdjustTo__c = null;
            newQuote.Name = 'Copy:' + oldQuote.Name;
            insert newQuote;

            // 拷贝报价产品
            List<QuoteProduct__c> newList = new List<QuoteProduct__c>();
            for (QuoteProduct__c oldQp : oldList) {
                QuoteProduct__c newQp = oldQp.clone(false, true);
                newQp.Quote__c = newQuote.Id;
                newList.add(newQp);
            }
            insert newList;

            return newQuote.Id;
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}